import json
import os

from flask import Flask, send_from_directory, request, make_response, jsonify
from werkzeug.utils import secure_filename

import scripts.image_tools as image_tools
from scripts.http import allow_cors
from config.config import get_config

app = Flask(__name__)

os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'


root_path = get_config()['root']
tool = image_tools.ImageTools()
#max_limit 默认无限制 若设置，则限制读取数量
features,filenames = tool.build_feature_database(root_path)

@app.route('/',methods=['POST'])
@allow_cors
def index():
    request_file = request.files['file']
    if secure_filename(request_file.filename):
        res = tool.search_similar_images(request_file,features,filenames,top_k=60)
        _res = []
        for filename,score in res:
            _img = filename[:0]+filename[1:]
            base = {
                'name': filename[1:],
                'score': float(score),
                'path':_img
            }
            _res.append(base)
        return jsonify(_res)
    else:
        return None

@app.route('/img')
def img():
    if request.method == 'GET':
        _id = request.args.get('id')
        file_name, file_extension = os.path.splitext(_id)
        if len(file_extension.strip()) == 0:
            file_name = _id + ".png"
        else:
            file_name = _id
        img_path = os.path.join(root_path+"\\", file_name)
        if _id is not None and os.path.exists(img_path) is True:
            rel_file_name = os.path.basename(img_path)
            base_path = os.path.dirname(img_path)
            return send_from_directory(base_path, rel_file_name)
        else:
            response = make_response('<b> 当前文件不存在 </b>')
            return response, 404
    else:
        return None


if __name__ == '__main__':
    app.run(debug=True, port=80)
